#!/usr/bin/python
# -*- coding: UTF-8 -*-
import json
from datetime import datetime
from kpautos.engine.case import Case
from kptest.config.enum import DeviceType, HostType, DeviceUtility
from extension.test_logic.RequestBase import RequestBase


class REDFISH_SESSION_004(Case):
    """
        Name:
            REDFISH_SESSION_004
        Label:
            修改会话服务
        PreCondition:
            BMC web service normal
        TestStep:
            1) PATCH https://BMC_IP/redfish/v1/SessionService，body里添加{"SessionTimeout":3600}需要get获取If-Match: ETag_value
        ExpectedResult:
            A) 执行响应码为200,查看会话时间更改
        Parameters:

        Author:
            baixin liuya
        Last Modified:

        Remark:

    """

    # 测试执行前配置等准备操作
    def pre_test_case(self):
        self.logger.info("Pre Test Case Start.... ")
        self.device_dut = self.resource.get_device(device_type=DeviceType.Server, utility=DeviceUtility.DUT)
        self.bmc_host = self.device_dut.get_host(host_type=HostType.BMC)
        self.bmc_ip = self.bmc_host.local_ip
        self.bmc_user = self.bmc_host.username
        self.bmc_pwd = self.bmc_host.password

        self.logger.info("获取Token")
        self.request = RequestBase(self.bmc_ip, self.bmc_user, self.bmc_pwd)
        return_code, session_id = self.request.create_session()
        self.assertIsNotNone(return_code)
        self.session_id = session_id

    # 测试步骤
    def procedure(self):
        url = "/redfish/v1/SessionService"
        self.log_step("Step1: 第1次查询会话服务")
        resp = self.request.get(url)
        if resp[0] != 200:
            self.logger.error(json.dumps(resp[1], indent=4, ensure_ascii=False))
            self.assertIsNotNone(None, f"返回码不是200，实际返回码{resp[0]}")
        self.logger.info(json.dumps(resp[1], indent=4, ensure_ascii=False))
        session_timeout = resp[1]['SessionTimeout']
        self.logger.info(f"会话SessionTimeout值: {session_timeout}")

        self.log_step("Step2: 修改新创建的会话资源")
        header = self.request.get_header(url)
        if_match_str = header['ETag']
        self.request.headers['If-Match'] = if_match_str

        json_text = {"SessionTimeout": 3600}
        resp = self.request.patch(url=url, params=json_text)
        rc = resp[0]
        self.assertIsNotNone(rc)
        content = resp[1]
        self.logger.info(f"修改后回显信息：\n{json.dumps(content, indent=4)}")

        self.log_step("Step3: 第2次查询会话服务")
        resp = self.request.get(url)
        if resp[0] != 200:
            self.logger.error({json.dumps(resp[1], indent=4, ensure_ascii=False)})
            self.assertIsNotNone(None, f"返回码不是200，实际返回码{rc}")
        self.logger.info(json.dumps(resp[1], indent=4, ensure_ascii=False))
        self.logger.info(f"会话SessionTimeout值: {resp[1]['SessionTimeout']}")

        self.log_step("Step4: 恢复会话服务SetTimeOut原值")
        header = self.request.get_header(url)
        if_match_str = header['ETag']
        self.request.headers['If-Match'] = if_match_str

        json_text = {"SessionTimeout": session_timeout}
        resp = self.request.patch(url=url, params=json_text)
        rc = resp[0]
        self.assertIsNotNone(rc)
        content = resp[1]
        self.logger.info(f"修改后回显信息：\n{json.dumps(content, indent=4)}")

    # 测试结束后恢复环境
    def post_test_case(self):
        resp = self.request.delete_session(self.session_id)
        self.assertIsNotNone(resp[0], "清除Token失败")
        self.logger.info("清除Token成功")
